package com.hdhere.application.controller;

import com.hdhere.application.service.MessageServer;
import com.hdhere.domain.UserInfo;
import com.hdhere.domain.common.rest.CallResult;
import com.hdhere.domain.common.util.LoginUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Created by dus on 2018/11/21.
 */
@Api(tags = "home")
@Controller
public class HomeController {

    @RequestMapping({"/","/index"})
    public String index( Map<String, Object> map){
        UserInfo user = LoginUtils.getLoginUser();
        map.put("user",user);
        map.put("cid", user.getId());
        return"index";
    }

    @GetMapping("/login")
    public String login(){

        return "login";
    }

    @PostMapping("/login")
    public String login(String username, String password, HttpServletRequest request, HttpServletResponse response, Map<String, Object> map) throws Exception{
        System.out.println("HomeController.login()");
        // 登录失败从request中获取shiro处理的异常信息。
        // shiroLoginFailure:就是shiro异常类的全类名.
        String msg = "";
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            token.clear();
            msg = e.getMessage();
        }

        String exception = (String) request.getAttribute("shiroLoginFailure");
        System.out.println("exception=" + exception);

        if (exception != null) {
            if (UnknownAccountException.class.getName().equals(exception)) {
                System.out.println("UnknownAccountException -- > 账号不存在：");
                msg = "UnknownAccountException -- > 账号不存在：";
            } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
                System.out.println("IncorrectCredentialsException -- > 密码不正确：");
                msg = "IncorrectCredentialsException -- > 密码不正确：";
            } else if ("kaptchaValidateFailed".equals(exception)) {
                System.out.println("kaptchaValidateFailed -- > 验证码错误");
                msg = "kaptchaValidateFailed -- > 验证码错误";
            } else {
                msg = "else >> "+exception;
                System.out.println("else -- >" + exception);
            }
            map.put("msg", msg);

            return "login";
        }
        response.sendRedirect("index");
        return "login";
    }

    @RequestMapping("/403")
    public String unauthorizedRole(){
        System.out.println("------没有权限-------");
        return "403";
    }

    /*//页面请求
    @GetMapping("/socket/{cid}")
    public ModelAndView socket(@PathVariable String cid) {
        ModelAndView mav=new ModelAndView("/index");
        mav.addObject("cid", LoginUtils.getLoginUser().getId());
        return mav;
    }*/

    @ApiOperation(value = "推送数据接口")
    @ResponseBody
    @PostMapping("/socket/push/{cid}")
    public CallResult pushToWeb(@PathVariable String cid, String message) {
        try {
            MessageServer.sendInfo(message,cid);
        } catch (IOException e) {
            e.printStackTrace();
            return CallResult.fail(cid+"#"+e.getMessage());
        }
        return CallResult.ok(cid);
    }
}
